package com.sinogrand.elevator.ui.screens

import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sinogrand.elevator.R
import kotlinx.coroutines.launch
import android.widget.Toast
import androidx.compose.ui.platform.LocalContext
import kotlin.math.cos
import kotlin.math.sin
import com.sinogrand.elevator.repository.LoginRepository
import com.sinogrand.elevator.utils.EnvironmentManager

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(
    onLoginSuccess: () -> Unit,
    onNavigateToEnvironmentSwitch: () -> Unit = {}
) {
    val context = LocalContext.current
    val environmentManager = remember { EnvironmentManager(context) }
    
    // 根据当前环境获取测试账号密码
    var phone by remember { mutableStateOf(environmentManager.getCurrentTestPhone()) }
    var password by remember { mutableStateOf(environmentManager.getCurrentTestPassword()) }
    
    // 监听环境变化，当从环境切换页面返回时更新账号密码
    // 每次组合时（包括从环境切换页面返回）都会重新读取最新的环境配置并更新账号密码
    LaunchedEffect(Unit) {
        phone = environmentManager.getCurrentTestPhone()
        password = environmentManager.getCurrentTestPassword()
    }
    var passwordVisible by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(false) }
    var isAgreementChecked by remember { mutableStateOf(true) }
    val coroutineScope = rememberCoroutineScope()
    val focusManager = LocalFocusManager.current
    
    // 酷炫背景动画
    val infiniteTransition = rememberInfiniteTransition(label = "coolBackground")
    val backgroundOffset by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(30000, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        ),
        label = "backgroundOffset"
    )
    
    val pulseAnimation by infiniteTransition.animateFloat(
        initialValue = 0.8f,
        targetValue = 1.2f,
        animationSpec = infiniteRepeatable(
            animation = tween(4000, easing = EaseInOutSine),
            repeatMode = RepeatMode.Reverse
        ),
        label = "pulse"
    )
    
    val waveAnimation by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 1f,
        animationSpec = infiniteRepeatable(
            animation = tween(6000, easing = EaseInOutSine),
            repeatMode = RepeatMode.Reverse
        ),
        label = "wave"
    )

    Box(
        modifier = Modifier
            .fillMaxSize()
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null
            ) {
                focusManager.clearFocus()
            }
    ) {
        // 酷炫背景层
        Canvas(
            modifier = Modifier.fillMaxSize()
        ) {
            val width = size.width
            val height = size.height
            val centerX = width / 2f
            val centerY = height / 2f
            
            // 动态渐变背景 - 调整对比度
            val gradient = Brush.radialGradient(
                colors = listOf(
                    Color(0xFF0A0A0A), // 深黑色
                    Color(0xFF1A1A2E), // 深蓝黑
                    Color(0xFF16213E), // 深蓝
                    Color(0xFF0F3460), // 深蓝色
                    Color(0xFF1E3A8A), // 蓝色
                    Color(0xFF2563EB)  // 更柔和的蓝色
                ),
                radius = width * 1.5f + backgroundOffset * 2f
            )
            
            // 绘制背景渐变
            drawRect(brush = gradient)
            
            // 绘制动态粒子效果
            for (i in 0..50) {
                val angle = (backgroundOffset + i * 7.2f) * (Math.PI / 180f)
                val radius = (width * 0.3f + i * 5f) * pulseAnimation
                val x = centerX + cos(angle).toFloat() * radius
                val y = centerY + sin(angle).toFloat() * radius
                
                val alpha = (0.1f + (i % 3) * 0.1f) * (1f - (i / 50f))
                val size = (2f + (i % 4)) * pulseAnimation
                
                drawCircle(
                    color = Color.White.copy(alpha = alpha),
                    radius = size,
                    center = Offset(x, y)
                )
            }
            
            // 绘制霓虹光效
            for (i in 0..3) {
                val waveOffset = waveAnimation * 360f + i * 90f
                val waveRadius = width * (0.4f + i * 0.2f)
                val waveX = centerX + cos(waveOffset * (Math.PI / 180f)).toFloat() * waveRadius
                val waveY = centerY + sin(waveOffset * (Math.PI / 180f)).toFloat() * waveRadius
                
                val neonColors = listOf(
                    Color(0xFF60A5FA), // 柔和的蓝色
                    Color(0xFF3B82F6), // 蓝色
                    Color(0xFF6366F1), // 柔和的紫色
                    Color(0xFF8B5CF6)  // 柔和的紫色
                )
                
                drawCircle(
                    color = neonColors[i].copy(alpha = 0.3f * waveAnimation),
                    radius = 100f * pulseAnimation,
                    center = Offset(waveX, waveY)
                )
            }
        }
        
        // 添加光效遮罩层 - 减少干扰
        Box(
            modifier = Modifier
                .fillMaxSize()
                .alpha(0.4f)
                .background(
                    brush = Brush.radialGradient(
                        colors = listOf(
                            Color.Transparent,
                            Color(0xFF1E3A8A).copy(alpha = 0.2f),
                            Color(0xFF0F172A).copy(alpha = 0.6f)
                        ),
                        radius = 800f
                    )
                )
        )
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.SpaceBetween
        ) {
            // 主要内容区域
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center,
                modifier = Modifier.weight(1f)
            ) {
                // 顶部装饰性元素
                Spacer(modifier = Modifier.height(20.dp))
            
            // 标题区域 - 添加发光效果
            Box(
                modifier = Modifier
                    .alpha(0.9f + 0.1f * pulseAnimation)
                    .shadow(
                        elevation = 16.dp,
                        shape = RoundedCornerShape(16.dp),
                        ambientColor = Color(0xFF3B82F6).copy(alpha = 0.3f),
                        spotColor = Color(0xFF60A5FA).copy(alpha = 0.2f)
                    )
            ) {
                Text(
                    text = "电梯运维一体化平台",
                    fontSize = 28.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .clickable(
                            interactionSource = remember { MutableInteractionSource() },
                            indication = null
                        ) {
                            // 点击进入环境切换页面（临时使用点击，后续可改为长按）
                            onNavigateToEnvironmentSwitch()
                        }
                        .graphicsLayer {
                            // 添加发光效果
                            // shadowElevation = 8f
                        }
                )
            }
            
            Spacer(modifier = Modifier.height(12.dp))
            
            Text(
                text = "Elevator O&M Integrated Platform",
                fontSize = 16.sp,
                color = Color(0xFF60A5FA).copy(alpha = 0.95f),
                textAlign = TextAlign.Center,
                fontWeight = FontWeight.Medium
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            Text(
                text = "请登录您的账户",
                fontSize = 18.sp,
                color = Color.White.copy(alpha = 0.9f),
                textAlign = TextAlign.Center,
                fontWeight = FontWeight.Medium
            )
            
            Spacer(modifier = Modifier.height(32.dp))
        
            // 登录表单 - 霓虹效果
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .alpha(0.95f)
                    .shadow(
                        elevation = 20.dp,
                        shape = RoundedCornerShape(24.dp),
                        ambientColor = Color(0xFF3B82F6).copy(alpha = 0.2f),
                        spotColor = Color(0xFF60A5FA).copy(alpha = 0.15f)
                    )
                    .graphicsLayer {
                        // 添加霓虹发光效果
                        shadowElevation = 12f
                    },
                shape = RoundedCornerShape(24.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color.White.copy(alpha = 0.95f)
                )
            ) {
                Column(
                    modifier = Modifier.padding(32.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 手机号输入框
                    OutlinedTextField(
                        value = phone,
                        onValueChange = { phone = it },
                        label = { 
                            Text(
                                "手机号",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium
                            ) 
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(12.dp)),
                        singleLine = true,
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = Color(0xFF1E3A8A),
                            unfocusedBorderColor = Color(0xFFE5E7EB),
                            focusedLabelColor = Color(0xFF1E3A8A),
                            unfocusedLabelColor = Color(0xFF6B7280)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    )
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    // 密码输入框
                    OutlinedTextField(
                        value = password,
                        onValueChange = { password = it },
                        label = { 
                            Text(
                                "密码",
                                fontSize = 14.sp,
                                fontWeight = FontWeight.Medium
                            ) 
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(12.dp)),
                        singleLine = true,
                        visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = Color(0xFF1E3A8A),
                            unfocusedBorderColor = Color(0xFFE5E7EB),
                            focusedLabelColor = Color(0xFF1E3A8A),
                            unfocusedLabelColor = Color(0xFF6B7280)
                        ),
                        shape = RoundedCornerShape(12.dp),
                        trailingIcon = {
                            IconButton(onClick = { passwordVisible = !passwordVisible }) {
                                Icon(
                                    imageVector = if (passwordVisible) Icons.Filled.Visibility else Icons.Filled.VisibilityOff,
                                    contentDescription = if (passwordVisible) "隐藏密码" else "显示密码",
                                    tint = Color(0xFF6B7280)
                                )
                            }
                        }
                    )
                
                    Spacer(modifier = Modifier.height(32.dp))
                    
                    // 登录按钮
                    Button(
                        onClick = {
                            // 收起键盘
                            focusManager.clearFocus()
                            
                            if (!isAgreementChecked) {
                                Toast.makeText(context, "请先勾选同意用户协议和隐私政策", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            if (phone.isBlank() || password.isBlank()) {
                                Toast.makeText(context, "请输入手机号和密码", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            // 验证手机号格式
                            if (!phone.matches(Regex("^1[3-9]\\d{9}$"))) {
                                Toast.makeText(context, "请输入正确的手机号", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            // 将手机号转换为Long
                            val mobileLong = try {
                                phone.toLong()
                            } catch (e: NumberFormatException) {
                                Toast.makeText(context, "手机号格式错误", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            isLoading = true
                            
                            // 调用真实登录接口
                            coroutineScope.launch {
                                try {
                                    val loginRepository = LoginRepository(context)
                                    val result = loginRepository.login(mobileLong, password)
                                    
                                    result.fold(
                                        onSuccess = { _ ->
                                            isLoading = false
                                            Toast.makeText(context, "登录成功！", Toast.LENGTH_SHORT).show()
                                            onLoginSuccess()
                                        },
                                        onFailure = { exception ->
                                            isLoading = false
                                            Toast.makeText(context, "登录失败：${exception.message}", Toast.LENGTH_SHORT).show()
                                        }
                                    )
                                } catch (e: Exception) {
                                    isLoading = false
                                    Toast.makeText(context, "登录失败：${e.message}", Toast.LENGTH_SHORT).show()
                                }
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(52.dp)
                            .clip(RoundedCornerShape(12.dp)),
                        enabled = !isLoading,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF1E3A8A),
                            disabledContainerColor = Color(0xFF9CA3AF)
                        ),
                        elevation = ButtonDefaults.buttonElevation(
                            defaultElevation = 4.dp,
                            pressedElevation = 8.dp
                        )
                    ) {
                        if (isLoading) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(20.dp),
                                color = Color.White,
                                strokeWidth = 2.dp
                            )
                        } else {
                            Text(
                                text = "登录",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color.White
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 分隔线
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                HorizontalDivider(
                    modifier = Modifier.weight(1f),
                    color = Color.White.copy(alpha = 0.3f),
                    thickness = 1.dp
                )
                Text(
                    text = "或",
                    modifier = Modifier.padding(horizontal = 20.dp),
                    fontSize = 14.sp,
                    color = Color.White.copy(alpha = 0.8f),
                    fontWeight = FontWeight.Medium
                )
                HorizontalDivider(
                    modifier = Modifier.weight(1f),
                    color = Color.White.copy(alpha = 0.3f),
                    thickness = 1.dp
                )
            }
            
            Spacer(modifier = Modifier.height(20.dp))
            
            // 微信登录
            OutlinedButton(
                onClick = {
                    // 收起键盘
                    focusManager.clearFocus()
                    
                    if (!isAgreementChecked) {
                        Toast.makeText(context, "请先勾选同意用户协议和隐私政策", Toast.LENGTH_SHORT).show()
                        return@OutlinedButton
                    }
                    // 显示功能开发中提示
                    Toast.makeText(context, "微信登录功能开发中，敬请期待！", Toast.LENGTH_SHORT).show()
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(52.dp)
                    .clip(RoundedCornerShape(12.dp)),
                enabled = !isLoading,
                colors = ButtonDefaults.outlinedButtonColors(
                    containerColor = Color.White,
                    contentColor = Color(0xFF1E3A8A),
                    disabledContainerColor = Color(0xFFF3F4F6),
                    disabledContentColor = Color(0xFF9CA3AF)
                ),
                border = ButtonDefaults.outlinedButtonBorder.copy(
                    brush = Brush.horizontalGradient(
                        colors = listOf(Color.White, Color.White)
                    ),
                    width = 1.dp
                ),
                elevation = ButtonDefaults.buttonElevation(
                    defaultElevation = 2.dp,
                    pressedElevation = 4.dp
                )
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    // 微信图标
                    Image(
                        painter = painterResource(id = R.drawable.weixin),
                        contentDescription = "微信",
                        modifier = Modifier.size(24.dp)
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Text(
                        text = "微信登录",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1E3A8A)
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(20.dp))
            }
            
            // 用户协议勾选 - 固定在底部，支持多行显示
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 32.dp), // 为物理按键区域留出空间
                verticalAlignment = Alignment.CenterVertically
            ) {
                Checkbox(
                    checked = isAgreementChecked,
                    onCheckedChange = { isAgreementChecked = it },
                    colors = CheckboxDefaults.colors(
                        checkedColor = Color(0xFF1E3A8A),
                        uncheckedColor = Color(0xFF9CA3AF)
                    )
                )
                Spacer(modifier = Modifier.width(8.dp))
                Column(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.Center
                ) {
                    Text(
                        text = buildAnnotatedString {
                            append("我已阅读并同意")
                            withStyle(
                                style = SpanStyle(
                                    color = Color(0xFF60A5FA),
                                    fontWeight = FontWeight.Bold
                                )
                            ) {
                                append("《用户协议》")
                            }
                            append("和")
                            withStyle(
                                style = SpanStyle(
                                    color = Color(0xFF60A5FA),
                                    fontWeight = FontWeight.Bold
                                )
                            ) {
                                append("《隐私政策》")
                            }
                        },
                        fontSize = 12.sp,
                        color = Color.White.copy(alpha = 0.95f),
                        fontWeight = FontWeight.Medium,
                        lineHeight = 18.sp,
                        modifier = Modifier.clickable { 
                            Toast.makeText(context, "点击查看用户协议和隐私政策", Toast.LENGTH_SHORT).show()
                            // 这里可以添加跳转到协议页面的逻辑
                        }
                    )
                }
            }
        }
        
        // 加载遮罩层
        if (isLoading) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black.copy(alpha = 0.5f))
                    .clickable { /* 阻止点击穿透 */ },
                contentAlignment = Alignment.Center
            ) {
                Card(
                    modifier = Modifier
                        .padding(32.dp)
                        .clip(RoundedCornerShape(16.dp)),
                    colors = CardDefaults.cardColors(containerColor = Color.White),
                    elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(24.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(32.dp),
                            color = Color(0xFF1E3A8A),
                            strokeWidth = 3.dp
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = "登录中...",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Medium,
                            color = Color(0xFF1E3A8A)
                        )
                    }
                }
            }
        }
    }
}